package com.appstore.action;

import org.apache.struts2.ServletActionContext;

import com.appstore.dao.IAdministratorrDao;
import com.appstore.dao.impl.AdministratorDaoimpl;
import com.appstore.exception.DaoException;
import com.opensymphony.xwork2.ActionSupport;

/**
 * AdministratorAction offer login interface to check admin login
 * 
 * @author zhbhun
 * 
 */
public class AdministratorAction extends ActionSupport {

	private IAdministratorrDao administratorrDao;
	private String username;
	private String password;
	private String tip;
	private String newPwd;
	private String checkingPwd;

	public AdministratorAction() {
		administratorrDao = AdministratorDaoimpl.getAdministratorDaoimpl();
	}

	/**
	 * login check.
	 * 
	 * @return
	 * @throws Exception
	 */
	public String login() throws Exception {
		Integer id = -1;
		try {
			id = administratorrDao.findAdministrator(this.username,
			        this.password);
		} catch (DaoException e) {
			throw new Exception("login error", e);
		}
		if (id == -1) {
			this.setTip("用户名或 密码错误");
			return "input";
		} else {
			this.setTip("登陆成功");
			ServletActionContext.getRequest().getSession()
			        .setAttribute("adminId", id);
			return "success";
		}
	}

	public String logout() {
		ServletActionContext.getRequest().getSession()
		        .setAttribute("adminId", null);
		return "logout";
	}

	public String changePassword() throws Exception {
		Integer id = (Integer) ServletActionContext.getRequest().getSession()
		        .getAttribute("adminId");
		if (id == null) {
			return "relogin";
		} else {
			if (newPwd.equals(checkingPwd)) {
				try {
					administratorrDao.changePassword(id, newPwd);
				} catch (DaoException e) {
					throw new Exception("Changing password has error", e);
				}
				return "change_success";
			} else {
				return "change_fail";
			}
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getTip() {
		return tip;
	}

	public void setTip(String tip) {
		this.tip = tip;
	}

	public String getNewPwd() {
		return newPwd;
	}

	public void setNewPwd(String newPwd) {
		this.newPwd = newPwd;
	}

	public String getCheckingPwd() {
		return checkingPwd;
	}

	public void setCheckingPwd(String checkingPwd) {
		this.checkingPwd = checkingPwd;
	}

}
